import React from 'react'
import {StyleSheet, AsyncStorage, View, TouchableOpacity, Image, Text} from 'react-native'
import {persistStore, autoRehydrate} from 'redux-persist'
import {create} from 'dva-core'
import createLoading from 'dva-loading'
import {Provider} from 'react-redux'
import RouterComponent from './router'
import PushHandle from './push'
import models from './model/index'
import {Carousel, Toast} from 'antd-mobile'
import {SCREEN} from './assets/styles/index'
import {ERROR_MSG_DURATION} from './utils/constant'
import Alipay from 'react-native-wtfssd-alipay'

Alipay.registerApp('easylife');

const SYS_STORAGE_KEY = "STORAGE_KEY_SYS";
const app = create({
    extraEnhancers: [autoRehydrate()],
    onError: (e) => {
        console.log('app have catch a error:', e);
        Toast.fail(e.message, ERROR_MSG_DURATION);
    },
});
app.use(createLoading());
const initModels = () => {
    models.map((mode) => {
        app.model(mode);
    })
};

initModels();
app.start();

class Guide extends React.Component {
    constructor() {
        super();
        this.state = {
            slider: [require('./assets/image/guide1.png'), require('./assets/image/guide2.png'), require('./assets/image/guide3.png'),],
        }
    }

    render() {
        return (
            <View style={Style.guide}>
                <Carousel dots={false}>
                    {this.state.slider.map((item, index) => {
                        return (
                            <TouchableOpacity activeOpacity={1}
                                              key={index}
                                              onPress={this.props.start}
                                              disabled={index !== this.state.slider.length - 1}>
                                <Image source={item} style={{
                                    height: SCREEN.height,
                                    width: SCREEN.width,
                                }}
                                       resizeMode={'stretch'}
                                />
                            </TouchableOpacity>
                        )
                    })}
                </Carousel>
            </View>
        )
    }
}


const Launch = (props) => {
    return (
        <View style={[Style.guide, Style.launch]}>
            <Image source={require('./assets/image/activity_welcome.png')} style={Style.guide}/>

            <TouchableOpacity style={Style.btn} onPress={props.onSkip}>
                <Text style={{color: '#333'}}>{`${props.time}s 跳过`}</Text>
            </TouchableOpacity>
        </View>
    )
};

class AppEl extends React.Component {
    timer = null;

    constructor(props) {
        super(props);
        this.state = {
            firstLaunch: true,
            loading: true,
            time: 1,
        };
        persistStore(app._store, {
                storage: AsyncStorage
            },
            () => {
                this.setState({
                    loading: true
                });
                this.timer = setInterval(() => {
                    let time = this.state.time;
                    if (time > 0) {
                        this.setState({
                            time: time - 1
                        })
                    } else {
                        this.setState({
                            loading: false
                        });
                        clearInterval(this.timer);
                    }

                }, 1000);
                AsyncStorage.getItem(SYS_STORAGE_KEY).then((data) => {
                    if (data) {
                        this.setState({
                            firstLaunch: JSON.parse(data).firstLaunch
                        })
                    } else {
                        this.setState({
                            firstLaunch: true
                        })
                    }
                })
            }
        );
    }

    componentWillMount() {
        PushHandle.init();
    }

    componentDidMount() {
    }

    componentWillUnmount() {
        PushHandle.destroy();
    }

    start() {
        AsyncStorage.setItem(SYS_STORAGE_KEY, JSON.stringify({
            firstLaunch: false
        }));
        this.setState({
            firstLaunch: false
        })
    }

    skip = () => {
        this.setState({
            loading: false,
            time: 1,
        });
        clearInterval(this.timer);
    };


    render() {

        const {firstLaunch, loading, time} = this.state;
        if (loading) {
            return <Launch time={time} onSkip={this.skip}/>
        } else {
            if (firstLaunch || typeof firstLaunch === 'undefined') {
                return <Guide start={this.start.bind(this)}/>
            } else {
                return (
                    <Provider store={app._store}>
                        <RouterComponent/>
                    </Provider>
                )
            }
        }

    }
}

const Style = StyleSheet.create({
    container: {
        display: 'flex',
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },

    guide: {
        width: SCREEN.width,
        height: SCREEN.height,
    },
    launch: {
        position: "relative",
    },
    btn: {
        position: 'absolute',
        top: 20,
        right: 20,
        borderRadius: 10,
        paddingHorizontal: 20,
        paddingVertical:8,
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor:'#f4f4f4',
    }
});

export default AppEl
